import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yi_shop/model/store.dart';
import 'package:yi_shop/ui/scroll_refresh_config.dart';
import 'package:yi_shop/utils/colors.dart';
import 'package:yi_shop/utils/styles.dart';
import 'package:yi_shop/utils/tools.dart';

class StoreListController extends GetxController {
  RxList<StoreListModel> pageList = RxList([]);

  RefreshController refreshController = RefreshController();

  @override
  void onInit() {
    pageList.add(StoreListModel(
        name: '韩都衣舍旗舰店',
        logo:
            'https://gw.alicdn.com/imgextra/i4/O1CN01GB2vZ01Zb96e14IyR_!!6000000003212-2-tps-64-64.png',
        imgs: [
          'https://img.alicdn.com/bao/uploaded/i2/2353877523/O1CN01ziGHFh25RaSlHReVO_!!0-item_pic.jpg',
          'https://img.alicdn.com/bao/uploaded/i4/2873181571/TB2bO9Dm4tmpuFjSZFqXXbHFpXa_!!2873181571.jpg',
          'https://img.alicdn.com/bao/uploaded/i4/651143977/O1CN01D7JQlU1fFW6OW4FDz_!!0-item_pic.jpg'
        ],
        collect: 3597,
        year: 3));
    initData();
    super.onInit();
  }

  Future<void> onRefresh() async {
    /// 发起请求
    await Future.delayed(const Duration(milliseconds: 2000));
    refreshController.refreshCompleted(resetFooterState: true);
  }

  Future<void> onLoading() async {
    /// 发起请求
    await Future.delayed(const Duration(milliseconds: 2000));

    /// if failed, use loadFailed(), if no data return, use LoadNodata()
    if (pageList.length > 32) {
      return refreshController.loadNoData();
    }

    /// 添加数据
    initData();

    /// 完毕
    refreshController.loadComplete();
  }

  void initData() {
    var r = Random.secure();
    for (var i = 0; i < 10; i++) {
      pageList.add(StoreListModel(
          name: '韩都衣舍旗舰店',
          logo:
              'https://img.alicdn.com/imgextra/i2/O1CN016h0JiX1WmeD9p64rg_!!6000000002831-2-tps-52-52.png',
          imgs: [
            'https://img.alicdn.com/bao/uploaded/i1/1901619097/O1CN01eyhpD12H4TkHeSTIc_!!0-item_pic.jpg',
            'https://img.alicdn.com/bao/uploaded/i2/3171703590/O1CN01FRVMFw1cOGnTcLCoR_!!0-item_pic.jpg',
            'https://img.alicdn.com/bao/uploaded/i3/1987669206/O1CN01pmvpMo2HsP88tYMWP_!!0-item_pic.jpg'
          ],
          year: r.nextInt(100),
          collect: r.nextInt(10000)));
    }
  }
}

class StoreListPage extends GetView<StoreListController> {
  const StoreListPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        leading: ToolsUtils.builderLeading(),
        title: Text(
          '韩都衣舍店铺',
          style: StylesUtils.customTextStyle(
              fontWeight: FontWeight.w700, fontSize: StylesUtils.fontSize18),
        ),
      ),
      body: Obx(() => scrollRefreshConfig(context)),
    );
  }

  ScrollRefreshConfig scrollRefreshConfig(BuildContext context) {
    return ScrollRefreshConfig(
      refreshController: controller.refreshController,
      onRefresh: controller.onRefresh,
      onLoading: controller.onLoading,
      child: listViewBuilder(context),
    );
  }

  ListView listViewBuilder(BuildContext context) {
    return ListView.builder(
      itemBuilder: (_, int index) {
        var row = controller.pageList[index];
        return Container(
          padding: const EdgeInsets.only(left: 25, right: 25, top: 15),
          decoration: const BoxDecoration(color: Colors.white),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text.rich(TextSpan(children: [
                    WidgetSpan(
                        child: CircleAvatar(
                          radius: 15,
                          backgroundImage: CachedNetworkImageProvider(row.logo),
                        ),
                        alignment: PlaceholderAlignment.middle),
                    TextSpan(
                        text: ' ${row.name}',
                        style: StylesUtils.customTextStyle(
                            color: ColorsUtils.color3333, fontSize: StylesUtils.fontSize16))
                  ])),
                  TextButton(
                      onPressed: () {},
                      style: ButtonStyle(
                          minimumSize: const WidgetStatePropertyAll(Size(70, 24)),
                          padding: const WidgetStatePropertyAll(EdgeInsets.zero),
                          alignment: Alignment.center,
                          shape: WidgetStatePropertyAll(RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(12),
                              side: BorderSide(
                                  color: ColorsUtils.parseColorFromHexString(
                                      ColorsUtils.colorF048))))),
                      child: Text(
                        '进店',
                        style: StylesUtils.customTextStyle(
                            color: ColorsUtils.colorF048, fontSize: StylesUtils.fontSize12),
                      ))
                ],
              ),
              Container(
                padding: const EdgeInsets.symmetric(vertical: 10),
                child: StaggeredGrid.count(
                  crossAxisCount: 3,
                  mainAxisSpacing: 20,
                  crossAxisSpacing: 10,
                  children: row.imgs
                      .map((e) => ClipRRect(
                            borderRadius: BorderRadius.circular(5.r),
                            child: CachedNetworkImage(
                              imageUrl: e,
                              width: 100,
                              height: 100,
                              fit: BoxFit.fill,
                            ),
                          ))
                      .toList(),
                ),
              ),
              Wrap(
                crossAxisAlignment: WrapCrossAlignment.center,
                alignment: WrapAlignment.start,
                spacing: 30,
                children: [
                  Chip(
                    backgroundColor: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF2f2),
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)),
                    labelPadding: const EdgeInsets.symmetric(horizontal: 8),
                    padding: EdgeInsets.zero,
                    side: BorderSide.none,
                    label: Text(
                      '${row.year}年老店',
                      style: StylesUtils.customTextStyle(
                          fontSize: StylesUtils.fontSize12, color: ColorsUtils.color9999),
                    ),
                  ),
                  Chip(
                    backgroundColor: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF2f2),
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)),
                    labelPadding: const EdgeInsets.symmetric(horizontal: 8),
                    padding: EdgeInsets.zero,
                    side: BorderSide.none,
                    label: Text(
                      '收藏人数${row.collect}万',
                      style: StylesUtils.customTextStyle(
                          fontSize: StylesUtils.fontSize12, color: ColorsUtils.color9999),
                    ),
                  )
                ],
              )
            ],
          ),
        );
      },
      itemCount: controller.pageList.length,
    );
  }
}
